import {DictionariesGroup} from '@/api/resourceApi';

const state = {
    dictMap: {}
};

const getters = {

};

const actions = {
    getDictLabel({ dispatch }, dict) {
        return new Promise((resolve, reject) => {
            dispatch('getDict', dict.type).then(res => {
                for (let item of res) {
                    if (item.sysdict_code == dict.value) {
                        resolve(item.sysdict_name);
                        return;
                    }
                }
                resolve(dict.value);
            }).catch(err => {
                reject(err);
            });
        });
    },
    getDict({ commit, state }, key) {

        // 按字典接口配置，方便调用
        const group_key_map = {
            'vehicle_type': '1002', 'plate_color': '1003', 'vehicle_color': '1004', 'station_type': '2003',
            'crossing_type': '1073', 'front_type': '1012', 'cross_type': '1018', 'camera_type': '1021', 'road_type': '1072',
            'lane_direction': '1014', 'lane_type': '1090', 'illegal-condition': '1095'
        };

        return new Promise((resolve, reject) => {
            if (key in state.dictMap) {
                resolve(state.dictMap[key]);
            } else {
                let group_key = group_key_map[key];
                DictionariesGroup({
                    Group: group_key
                }).then(res => {
                    // console.log(res);
                    const resdata = res.res;
                    let data = [];
                    if (resdata.LoginStatus == 'T') {
                        data = resdata.SiteMap;
                        if (data && data.length > 0) {
                            commit('addDict', {
                                key: key,
                                data: data
                            });
                        }

                    }
                    resolve(data);
                }).catch(error => {
                    reject(error);
                });
            }
        });
    }
};

const mutations = {
    addDict(state, data) {
        state.dictMap[data.key] = data.data;
    }
};

export default {
    namespaced: true,
    state,
    actions,
    getters,
    mutations
};
